// pages/share/share.js
var pinyin = require('../../utils/convert2pinyin.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    originWords:'',
    targetWords:'',
    images:[],
    theOne:-1,
    wordNum:0
  },
  codeIsUpper: function (code){
    return code === code.toUpperCase()
  },
  shuffle: function (a) {
    var len = a.length;
    for(var i = 0; i<len - 1; i++) {
      var index = parseInt(Math.random() * (len - i));
      var temp = a[index];
      a[index] = a[len - i - 1];
      a[len - i - 1] = temp;
    }
},
  bindFormSubmit: function (e) {
    var words = e.detail.value.words
    var result = pinyin.getFullChars(words).toLowerCase().replace(/[^0-9a-zA-Z]/g, "")
    if (result == this.data.targetWords.toLowerCase().replace(/[^0-9a-zA-Z]/g, "")){
      wx.showModal({
        title: '恭喜,猜对啦！',
        content: '他/她想对你说：\n'+this.data.originWords,
      })
    }else{
      wx.showToast({
        title: '别急，你可以的',
        icon: 'loading'
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var targetWords = options.targetWords
    this.setData({
      originWords: options.originWords,
      targetWords: targetWords
    })
    var images=[]
    var dict = {
      'zh': 1,
      'ch': 2,
      'sh': 3,
      'ng': 4
    }
    for (var i = 0; i < targetWords.length; i++){
      var code = targetWords.charAt(i)
      //去除非字母、数字字符
      if (code.match(/[0-9a-zA-Z]/g) == null) {
        // console.log(code)
        continue
      }
      var isUpper = this.codeIsUpper(code)
      //每个字首字母大写，统计字数
      if(isUpper){
        this.setData({
          wordNum: this.data.wordNum+1
        })
      }
      if (i + 1 < targetWords.length) {
        var tryCode = code + targetWords.charAt(i + 1)
        tryCode = tryCode.toLowerCase()
        if (tryCode in dict) {
          images.push(['../../images/' + tryCode.toLowerCase() + '.png', isUpper])
          i = i + 1
          continue
        }
      }
      images.push(['../../images/' + code.toLowerCase() +'.png', isUpper])
    }
    // console.log(images)
    this.shuffle(images)
    this.setData({
      images: images
    })
  },

  changeTheOne: function(opt){
    console.log(opt)
    var curIndex = opt.currentTarget.dataset.idx
    var images = this.data.images
    if(this.data.theOne<0){
      //记录下第一个点过的字母
      this.setData({
        theOne: curIndex
      })
    }else{
      //已经点过一个，此次执行交换
      var theOne = this.data.theOne
      var tmp = images[curIndex]
      images[curIndex] = images[theOne]
      images[theOne] = tmp

      //执行交换后，决策是否正确
      if (this.decideResult(images)) {
        wx.showModal({
          title: '恭喜你，猜对啦!',
          content: '他/她想对你说：' + this.data.originWords,
          duration: 2000,
          success:function(res){
            if (res.confirm) {
              // console.log('用户点击确定')
            } else if (res.cancel) {
              // console.log('用户点击取消')
            }
          }
        })
      }
      //重置选择索引
      this.setData({
        theOne: -1
      })
    }
    
    //重置图片
    this.setData({
      images: images
    })
  },

  decideResult: function(images){
    var curWordsPinyin=''
    for(var i=0;i<images.length;i++){
      var src = images[i][0]
      var l = src.lastIndexOf('/')
      var p = src.lastIndexOf('.')
      curWordsPinyin += src.substr(l + 1, p - l - 1)
    }
    // console.log(curWordsPinyin, this.data.targetWords)
    var targetWords = this.data.targetWords.toLowerCase().replace(/[^0-9a-zA-Z]/g, "");
    if (curWordsPinyin.toLowerCase() == targetWords){
      return true
    }else{
      return false
    }
  },

  backHome: function(){
    wx.redirectTo({
      url: '/pages/index/index',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return{
      title:"猜一猜我想对你说什么？",
      path: '/pages/share/share?originWords=' + this.data.originWords + '&targetWords=' + this.data.targetWords
    }
  }
})